const path = require('path');
const express = require('express');
const router = express.Router();
const {CODE} = require('../utils/constants')
// 引入user模型
const userModel = require('../db/model/userModel')
// 导入formidable
const formidable = require('formidable');
// 用户分页列表接口 page 当前页 limit 每页显示几条
router.get('/user/:page/:limit', async (req,res)=>{
    /**
     *  总条数： totalNum
     *  总页数：totalPage = Math.ceil(totalNum/limit)
     *  skipNum = (page - 1) * limit 
     */
    let {page, limit} = req.params;
    try{
        let totalNum = await userModel.count({}); // 获取所有用户的条数
        // console.log(totalNum);
        let totalPage = Math.ceil(totalNum/limit)
        // console.log('totalPage: ', totalPage);
        let skipNum = (page - 1) * limit;
        // console.log('skipNum: ', skipNum);
        // 获取用户分页列表数据
        let users = await userModel.find({}).skip(skipNum).limit(limit).select({pwd:0})
        console.log('users: ', users);
        res.json({
            code:CODE.SUCCESS,
            data:{
                users,
                totalPage
            },
            message:'获取分页列表成功'
        })
    }catch(e){
        res.json({
            code:CODE.SERVER_ERROR,
            data:null,
            message:'网络链接异常'
        })
    }
})

// 添加用户路由  username pwd  头像图片
router.post('/user', (req, res)=>{
    const form = formidable({
        uploadDir: path.resolve(__dirname, '../public/upload'), // 上传文件路径[目录必须存在]
        keepExtensions:true
    })
    form.parse(req, async (err, fields, files)=>{
        // console.log('fields: ', fields);// 普通数据
        console.log('files: ', files);// 文件数据
        let avatarPath = '/upload/' + files['profileFile'].newFilename;
        // console.log('avatarPath: ',avatarPath);
        fields.profile = avatarPath
        try{
            let user = await userModel.create(fields)
            
            let responseData = {
                _id:user._id,
                username:user.username,
                profile:user.profile,
                create_time:user.create_time
            }
            res.json({
                code:CODE.SUCCESS,
                data:responseData,
                message:'用户添加成功'
            })

        }catch(e){
            res.json({
                code:CODE.SERVER_ERROR,
                data:null,
                message:'网络连接异常'
            })
        }
    })
})
// 根据query参数_id 查询用户数据
// localhost:9999/admin/user?id=xxjklej123
router.get('/user', async (req, res)=>{
    // 1.获取id
    let {id} = req.query;
    try{
        let user = await userModel.findOne({_id:id})
        res.json({
            code:CODE.SUCCESS,
            data:user,
            message:'获取用户数据成功'
        })
    }catch(e){
        res.json({
            code:CODE.SERVER_ERROR,
            data:null,
            message:'网络链接异常'
        })
    }
})
// 根据id更新用户信息
router.put('/user', async (req, res)=>{
    const form = formidable({
        uploadDir: path.resolve(__dirname, '../public/upload'), // 上传文件路径[目录必须存在]
        keepExtensions:true
    })
    form.parse(req, async (err, fields, files)=>{
        if(err){
            return res.json({
                code:CODE.SERVER_ERROR,
                message:'图片上传失败'
            })
        }
        // 获取用户提交的文本数据 _id 、username
        let {_id, username} = fields;
        // 拼接图片路径
        let profile = '/upload/' + files['profileFile'].newFilename
        try{
            // 根据_id 更新数据库
            await userModel.updateOne({_id}, {username, profile})
            res.json({
                code:CODE.SUCCESS,
                message:'更新成功'
            })
        }catch(e){
            res.json({
                code:CODE.SERVER_ERROR,
                data:null,
                message:'网络链接异常'
            })
        }
    })
})

module.exports = router;